package com.edgar.log4j.ch01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.NDC;
import org.apache.log4j.PropertyConfigurator;

public class NDCMDCServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 568179398428938100L;

	private static Logger logger = Logger.getLogger(NDCMDCServlet.class);

	@Override
	public void init() throws ServletException {
		super.init();
		String configFile = getInitParameter("log4j-conf");
		PropertyConfigurator.configureAndWatch(getServletContext().getRealPath(
				"/")
				+ configFile);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String remoteAddress = req.getRemoteAddr();
		String remoteHost = req.getRemoteHost();
		NDC.push(remoteHost);
		MDC.put("remoteAddress", remoteAddress);

		logger.info("invoked the NDCMDCServlet...");
		PrintWriter writer = resp.getWriter();
		writer.println("Check your web server console...");
		writer.flush();
		writer.close();
	}

}
